<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区 -->
        <el-card>
            <!-- 添加角色按钮区 -->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addRolesVisible=true">添加角色</el-button>
                </el-col>
            </el-row>

            <!-- 角色列表区 -->
            <el-table :data="roleList" border stripe>
                <!-- 展开列 -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bdbottom',i1===0?'bdtop':'','vcenter']"
                            v-for="(item1,i1) in scope.row.children" :key="item1.id">
                            <!-- 渲染一级权限 -->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row,item1.id)">
                                    {{item1.authName}}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级,三级权限 -->
                            <el-col :span="19">
                                <el-row v-for="(item2,i2) in item1.children" :key="item2.id"
                                    :class="[i2 === 0 ? '' : 'bdtop' ,'vcenter']">
                                    <el-col :span='6'>
                                        <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">
                                            {{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>

                                    <el-col :span="18">
                                        <el-tag type='warning' v-for="(item3,i3) in item2.children" :key="item3.id"
                                            closable @close="removeRightById(scope.row,item3.id)">
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>

                        </el-row>

                    </template>
                </el-table-column>

                <!-- 索引列 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope" width="300px">
                        <el-button type="primary" size="mini" icon="el-icon-edit" @click="changeRoles(scope.row.id)">编辑
                        </el-button>
                        <el-button type="danger" size="mini" icon="el-icon-delete" @click="rolesDelete(scope.row.id)">删除
                        </el-button>
                        <el-button type="warning" size="mini" icon="el-icon-setting"
                            @click="showSetRightDialog(scope.row)">分配权限
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 添加角色 -->
        <el-dialog title="添加角色" :visible.sync="addRolesVisible" width="50%" @close="addRolesClose">
            <!-- 内容主题区 -->
            <el-form :model="addRolesList" :rules="addRolesRules" ref="addRolesRef" label-width="120px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRolesList.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRolesList.roleDesc"></el-input>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addRolesVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRoles">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改角色对话框 -->
        <el-dialog title="修改角色" :visible.sync="dialogRolesVisible" @close="rolesDialogClosed">
            <el-form :model="changeRolesList" ref="changeRolesRef" :rules="changeRolesRules" label-width="80px">
                <el-form-item label="角色名称">
                    <el-input v-model="changeRolesList.roleName" disabled></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="changeRolesList.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogRolesVisible = false">取 消</el-button>
                <el-button type="primary" @click="changeRolesInfo">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 分配权限的对话框 -->
        <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClose">
            <!-- 树形控件 -->
            <el-tree :data="rightList" :props="treeProps" show-checkbox node-key="id" default-expand-all
                :default-checked-keys="defKeys" ref='treeRef'>

            </el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
    export default {

        data() {
            return {
                //所有角色列表数据
                roleList: [],
                addRolesVisible: false,
                dialogRolesVisible: false,
                setRightDialogVisible: false,
                // 规则
                addRolesRules: {
                    roleName: [{ required: true, message: '请输入角色名', trigger: 'blur' }, { min: 1, max: 10, message: '角色名长度大于1小于10', trigger: 'blur' }],
                    roleDesc: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
                },
                changeRolesRules: {
                    roleDesc: [{ required: true, message: '请修改角色描述', trigger: 'blur' }]

                },
                addRolesList: {
                    roleName: '',
                    roleDesc: ''
                },
                changeRolesList: {},
                // 所有权限的数据
                rightList: [],
                // 树形控件属性绑定对象
                treeProps: {
                    label: 'authName',
                    children: 'children'
                },
                // 默认选择的ID节点值
                defKeys: [],
                // 当前即将分配角色的ID
                roleId: ''

            }

        },
        created() {
            this.getRolesList()

        },
        methods: {
            async getRolesList() {
                const { data: res } = await this.$http.get('roles')
                if (res.meta.status !== 200) {
                    return this.$message.error('获取角色列表失败')
                }
                this.roleList = res.data
                // console.log(this.roleList);
            },
            //添加角色区
            addRolesClose() {
                this.$refs.addRolesRef.resetFields()
            },
            addRoles() {
                this.$refs.addRolesRef.validate(async valid => {
                    if (!valid) return
                    const { data: res } = await this.$http.post('roles', this.addRolesList)
                    // console.log(res);
                    if (res.meta.status !== 201) {
                        this.$message.error('添加角色失败')
                    }
                    this.$message.success('添加角色成功!')
                    this.addRolesVisible = false
                    this.getRolesList()
                })
            },
            async changeRoles(id) {
                const { data: res } = await this.$http.get('roles/' + id)
                if (res.meta.status !== 200) {
                    return this.$message.error('查询失败')
                }
                this.changeRolesList = res.data
                this.dialogRolesVisible = true
            },
            rolesDialogClosed() {
                this.$refs.changeRolesRef.resetFields()
            },
            changeRolesInfo() {
                this.$refs.changeRolesRef.validate(async valid => {
                    if (!valid) return
                    const { data: res } = await this.$http.put('roles/' + this.changeRolesList.roleId,
                        {
                            roleName: this.changeRolesList.roleName,
                            roleDesc: this.changeRolesList.roleDesc
                        })
                    if (res.meta.status !== 200) {
                        return this.$message.error('修改失败')
                    }
                    this.dialogRolesVisible = false
                    this.getRolesList()
                    this.$message.success('修改成功')

                })
            },
            async rolesDelete(id) {
                const confirmResult = await this.$confirm('确定删除此角色吗？', 'Tips', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)
                if (confirmResult == 'cancel') {
                    return this.$message.info('已取消删除')
                }
                const { data: res } = await this.$http.delete('roles/' + id)
                if (res.meta.status !== 200) {
                    return this.$message.error('删除失败')
                }
                this.$message.success('删除成功')
                this.getRolesList()

            },
            // 根据id删除对应的权限
            async removeRightById(role, rightId) {
                const confirmRes = await this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)
                if (confirmRes !== 'confirm') {
                    return this.$message.info('取消了删除')
                }
                const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
                if (res.meta.status !== 200) {
                    return this.$message.error('删除授权失败')
                }
                // this.getRolesList()
                role.children = res.data
            },
            // 展示树形分配权限的对话框
            async showSetRightDialog(role) {
                this.roleId = role.id
                const { data: res } = await this.$http.get('rights/tree')
                if (res.meta.status !== 200) {
                    this.$message.error('获取权限失败')
                }
                this.rightList = res.data
                // console.log(this.rightList);
                this.getLeafKeys(role, this.defKeys)
                this.setRightDialogVisible = true
            },
            // 通过递归函数的形式，获取角色全部三级权限的ID保存到defkey中
            getLeafKeys(node, arr) {
                // 如果node节点不包含children属性则是三级节点
                if (!node.children) {
                    return arr.push(node.id)
                }
                node.children.forEach(item => this.getLeafKeys(item, arr));
            },
            //监听分配权限对话框的关闭事件
            setRightDialogClose() {
                this.defKeys = []
            },
            async allotRights() {
                const keys = [
                    ...this.$refs.treeRef.getCheckedKeys(),
                    ...this.$refs.treeRef.getHalfCheckedKeys(),
                ]
                // console.log(keys);
                const idStr = keys.join(',')
                const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
                if (res.meta.status !== 200) {
                    return this.$message.error('分配失败')
                }
                this.$message.success('分配成功')
                this.getRolesList()
                this.setRightDialogVisible = false

            }
        },
    }
</script>

<style scoped>
    .el-tag {
        margin: 10px;
    }

    .bdtop {
        border-top: 1px solid #ccc;
    }

    .bdbottom {
        border-bottom: 1px solid #ccc;
    }

    .vcenter {
        display: flex;
        align-items: center;
    }
</style>